package com.wing.robot.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.robot.model.entity.RobotTaskInfo;
import com.wing.robot.service.RobotTaskInfoService;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.robot.model.entity.RobotTask;
import com.wing.robot.model.request.RobotTaskForm;
import com.wing.robot.service.RobotTaskService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

/**
 *
 * @author
 */
@Slf4j
@Validated
@Api(value = "Admin-复合机器人任务管理", tags = "#/robot/robotTask")
@RestController("robotTaskController")
@RequestMapping("robot/admin/robotTask")
@RequiredArgsConstructor
public class RobotTaskController {

    private final RobotTaskService robotTaskService;
    private final RobotTaskInfoService robotTaskInfoService;


    @ApiOperation(value = "查询所有复合机器人任务", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<RobotTask> list(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "create_time") String sort
            ,@RequestParam(defaultValue = "asc") String order
            ,String name
            ,String code
            ,Long id
    ){

        Page<RobotTask> pg = new Page<>(page, limit);
        QueryWrapper<RobotTask> queryWrapper = new QueryWrapper<>();

        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            if (StringUtils.equals("asc", order)) {
                queryWrapper.orderByAsc(StrUtil.toUnderlineCase(sort));
            } else {
                queryWrapper.orderByDesc(StrUtil.toUnderlineCase(sort));
            }
        }
        if (StringUtils.isNotBlank(name)){
            queryWrapper.like("name",name);
        }
        if (StringUtils.isNotBlank(code)){
            queryWrapper.like("code",code);
        }
        if(id!=null){
            queryWrapper.eq("id",id);
        }
        IPage<RobotTask> list = robotTaskService.getBaseMapper().selectPage(pg, queryWrapper);
        list.getRecords().parallelStream().forEach(k -> {
            QueryWrapper<RobotTaskInfo> queryWrapper1 =new QueryWrapper<>();
            queryWrapper1.eq("task_id",k.getId());
            k.setInfoList(robotTaskInfoService.list(queryWrapper1));
        });
        return new PageResult<>(list.getRecords(), list.getTotal());
    }



    @ApiOperation(value = "添加复合机器人任务", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(@Validated(RobotTaskForm.Add.class) @RequestBody RobotTaskForm robotTaskForm) {
        try{
            robotTaskService.add(robotTaskForm);
            return JsonResult.success("添加成功");
        }catch(Exception e){
            log.error("添加失败:", e);
            return JsonResult.fail("添加失败"+e.getMessage());
        }
    }




    @ApiOperation(value = "修改复合机器人任务", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(@Validated(RobotTaskForm.Update.class) @RequestBody RobotTaskForm robotTaskForm) {
        RobotTask robotTask = robotTaskService.getById(robotTaskForm.getId());
        if(robotTask == null){
        return JsonResult.fail("修改失败！");
        }
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(RobotTask.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(robotTaskForm, robotTask, copyOptions);

        if(robotTaskForm.getInfoList()!=null){
            for (RobotTaskInfo robotTaskInfo:robotTaskForm.getInfoList()){
                if (robotTaskInfo.getId()!=null){//修改已经有的
                    robotTaskInfoService.updateById(robotTaskInfo);
                }else{//新增
                    robotTaskInfo.setTaskId(robotTask.getId());
                    robotTaskInfoService.getBaseMapper().insert(robotTaskInfo);
                }
            }
        }

        if (robotTaskService.updateById(robotTask)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }



    @ApiOperation(value = "删除复合机器人任务", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "robotTaskId", value = "复合机器人任务id", required = true, dataType = "Integer", paramType = "path")
    })
    @DeleteMapping("/{id}" )
    public JsonResult delete(@PathVariable("id") Long robotTaskId) {
        if (robotTaskService.removeById(robotTaskId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }





}
